package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.List;

import javax.validation.Valid;

import com.handu.luna.core.domain.promotion.CreditGoodsGoods;
import com.handu.luna.core.domain.promotion.Promotion;
import com.handu.luna.core.domain.search.CreditGoodsSearch;
import net.sf.json.JSONObject;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.promotion.CreditGoods;



@Controller
@RequestMapping("/promotion/goods/*")
public class CreditGoodsController extends BaseController{

    @RequestMapping(value = "list",method = RequestMethod.GET)
    public BossModel list(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {

        CreditGoodsSearch creditGoodsSearch;
        BossModel bossModel = createModel("promotion/goods/list");
		if(viewState != null && !viewState.trim().equals("")){
			//解析传递过来的查询json字符串
			creditGoodsSearch = (CreditGoodsSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), CreditGoodsSearch.class);
		}else{
			creditGoodsSearch = new CreditGoodsSearch();
            viewState = "";
		}
        return bossModel.add("creditGoodsList",context.getCreditGoodsRepository().findAll(CreditGoods.selectCondition(creditGoodsSearch),pageable))
                .add("creditGoodsSearch",creditGoodsSearch)
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState", viewState);
	}

    @RequestMapping(value = "list",method = RequestMethod.POST)
    public BossModel list(CreditGoodsSearch creditGoodsSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException {
        BossModel bossModel = createModel();
        return bossModel.add("creditGoodsList",context.getCreditGoodsRepository().findAll(CreditGoods.selectCondition(creditGoodsSearch),pageable))
                .add("creditGoodsSearch",creditGoodsSearch)
                .add("statusValues", Promotion.PromotionStatus.values())
                .add("viewState",Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(creditGoodsSearch).toString().getBytes("UTF-8")));
	}

	/*@RequestMapping(value="list")
	public BossModel list(@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE) Pageable pageable){
		return this.createModel("promotion/goods/list")
                .add("creditGoodsList", context.getCreditGoodsRepository().findAll(pageable));
	}*/
	
	@RequestMapping(value="edit/{id}")
	public BossModel edit(@PathVariable long id){
		return createModel("promotion/goods/info")
                .add("userRanks", context.getUserRankRepository().findAllNotSpecial())
                .add("creditGoods", context.getCreditGoodsRepository().findOne(id))
                .add("creditTypeValues", CreditGoods.CreditType.values());
	}
	
	@RequestMapping(value="save",method = RequestMethod.POST)
	public BossModel save(@Valid @ModelAttribute("creditGoods") final CreditGoods creditGoods, final BindingResult bindingResult, final ModelMap model, RedirectAttributes redirectAttributes){
		if(creditGoods.getStartTime() == null) {
			bindingResult.rejectValue("startTime", "misFormat", "请输入开始日期");
		}
		if(creditGoods.getEndTime() == null) {
			bindingResult.rejectValue("endTime", "misFormat", "请输入结束日期");
		}
		if(creditGoods.getStartTime() != null && creditGoods.getEndTime() != null) {
			if(creditGoods.getStartTime().compareTo(creditGoods.getEndTime()) != -1) {
				bindingResult.rejectValue("startTime", "misFormat", "开始时间必须小于结束时间");
			}
		}
//		if(creditGoods.getCreditGoodsName() .trim().equals("")){
//			bindingResult.rejectValue("creditGoodsName", "", "请输入名称");
//		}
		
		if (bindingResult.hasErrors()) {
			return createModel("promotion/goods/info")
                    .add("userRanks", context.getUserRankRepository().findAllNotSpecial())
                    .add("creditTypeValues", CreditGoods.CreditType.values());
		}
		String message = creditGoods.getSucessFlashMessage("");
		context.getCreditGoodsRepository().save(creditGoods);
		redirectAttributes.addFlashAttribute("message", message);
		return createModel("redirect:list");
	}
	
	@RequestMapping(value="add")
	public BossModel add(){

        CreditGoods creditGoods = new CreditGoods();
        creditGoods.setCreditType(CreditGoods.CreditType.CREDIT);

        return createModel("promotion/goods/info")
            .add("userRanks", context.getUserRankRepository().findAllNotSpecial())
            .add("creditGoods", creditGoods)
            .add("creditTypeValues", CreditGoods.CreditType.values());
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable,String viewState){
		//context.getCreditGoodsRepository().findOne(id);
        if(viewState == null || viewState.trim().equals("")){
            viewState = "";
        }

        List<CreditGoodsGoods> creditGoodsGoodsList = context.getCreditGoodsGoodsRepository().findByCreditGoodsId(id);
        for(CreditGoodsGoods creditGoodsGoods : creditGoodsGoodsList) {
            context.getCreditGoodsGoodsRepository().delete(creditGoodsGoods);
        }

		context.getCreditGoodsRepository().delete(id);
		return createModel("promotion/goods/creditGoods_table")
                .add("creditGoodsList",context.getCreditGoodsRepository().findAll(pageable))
                .add("viewState",viewState);
	}
}
